package selector;

import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author： pang-yun
 * @date： 2021-09-08 09:30
 * 功能目的 ：用于
 */

public class ReadNioSelectorServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        SelectionKey sscKey = ssc.register(selector, SelectionKey.OP_ACCEPT, null);
        ssc.bind(new InetSocketAddress(9999));

        while (true){
            // 阻塞  直到有事件才会进来
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    ServerSocketChannel serverSocketChannel  = (ServerSocketChannel) key.channel();
                    SocketChannel sc = serverSocketChannel.accept();
                    sc.configureBlocking(false);
                    sc.register(selector,SelectionKey.OP_READ,null);
                }else if (key.isReadable()){
                    SocketChannel socketChannel = (SocketChannel) key.channel();

                    ByteBuffer byteBuffer = ByteBuffer.allocate(32);

                    try {
                        int read = socketChannel.read(byteBuffer);
                        // 正常断开  取消事件
                        if (read==-1){key.cancel();}
                        if (read>0){
                            byteBuffer.flip();
                            while (byteBuffer.hasRemaining()){
                                byte b = byteBuffer.get();
                                System.out.print((char) b);
                            }
                        }
                        /// 异常 断开 取消事件
                    } catch (IOException e) {
                        socketChannel.socket().close();
                        socketChannel.close();
                        key.cancel();
                    }
                }
            }
        }
    }
}
